import React, { useEffect, useState } from 'react'
import { HashRouter as Router,Route, Switch,Redirect,useHistory,useLocation} from "react-router-dom";
import Login from './pages/login/login'
import Layout from './pages/layout/layout';
import {Provider} from 'react-redux';
import store, { useRedux } from './store/index';
import Action from './store/action';
import { useCreate } from './hooks/useCreate';

function App() {
  return (
    <Provider store={store}>
      <Router>
        <MyRouter />
      </Router>
    </Provider>
  )
}

export default App


const MyRouter = ()=>{
  const history = useHistory();
  const localtion = useLocation();
  const {dispatch} = useRedux();
  useEffect(()=>{
    history.listen((location,action)=>{
      dispatch({type:Action.ROUTER_CHANGE,payload:location.pathname});
    })
  },[dispatch])

  useCreate(()=>{
    dispatch({type:Action.INIT_ROUTER,payload:localtion.pathname})
  })
  
  return (
    <Switch>
      <Route path="/login">
        <Login />
      </Route>
      <Route path="/" >
        <RouterPromiss component={<Layout />} />
      </Route>
    </Switch>
  )
}


const RouterPromiss = (props:{component:JSX.Element})=>{
  let token = window.localStorage.getItem("token");
  // 判断如果路由中有token则直接进入
  const localtion = useLocation();
  const hanlderSearchObj = (str:string):object=>{
    let searchArr = str.split("?");
    let searchStr = "";
    if(searchArr.length>0){
      searchStr = searchArr[1];
    }
    let queryArr = searchStr.split("&");
    let obj:any = {};
    queryArr.forEach(item=>{
      let itemArr = item.split("=");
      obj[itemArr[0]] = itemArr[1];
    })
    return obj;
  }

  let query:any = {};
  if(localtion.search){
    query = hanlderSearchObj(localtion.search);
  }

  if(!token && query){
    token = query.token;
  }
  if(!token){
    return <Redirect to="/login" />
  }
  window.localStorage.setItem('token',token);
  return props.component
}